/*************************************************************
* File Name: SysTimerTick.c SysTimerTick.h
* Version:	 V1.01
* Release Date: 2025.8.1
* Author: Chen Shou Min
* 使用说明:时间片产生模块，产生5ms,10ms,100ms,1s,1min等基本时间片
* History:
	V1.00 首版软件
	V1.01 加入最大主循环时间计算	----陈首敏
*************************************************************/
#define		TICK_C

#include "Global.h"

unsigned char TimeFlag = 0;
unsigned char TimeFlagIRQ = 0;
unsigned long u32GlobalTime = 0;
unsigned long CycleTime = 0;
unsigned long MaxCycleTime = 0;

/**************************************************************
//Fuction GetTimeTick(unsigned char temp)
//Desrition:时间片查询
//Input:  时间类别
//Output: 到时间输出1，否则为0
//Author:陈首敏
***************************************************************/
unsigned char GetTimeTick(unsigned char temp)
{
	if(temp & TimeFlag)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}

/**************************************************************
//Fuction unsigned long GetFreeTimer(void)
//Desrition:获取自由时间
//Input:  
//Output: 当前时间，单位us。
//Author:陈首敏
***************************************************************/
unsigned long GetFreeTimer(void)
{
	return u32GlobalTime;
}

/**************************************************************
//Fuction TimeBaseTick_IRQ(void)
//Desrition:时间中断函数
//Input:  
//Output:
//Author:陈首敏
***************************************************************/
void TimeBaseTick_IRQ(void)
{
	static unsigned char TimeBaseCnt = 0;
	u32GlobalTime += TIME_ISR_US;
	TimeBaseCnt++;
	if(CycleTime < 0xffff)CycleTime ++;
    if( TimeBaseCnt >= (TIME_MIN_US/TIME_ISR_US) )
	{	TimeBaseCnt = 0;
		TimeFlagIRQ = 1;
	}
}

/**************************************************************
//Fuction void TimeProc(void)
//Desrition:时间总函数
//Input:  
//Output:
//Author:陈首敏
***************************************************************/
void TimeProc(void)
{
	static unsigned char uc10msCnt = 0;
	static unsigned char uc100msCnt = 0;
	static unsigned char uc1sCnt = 0;
	static unsigned char uc1minCnt = 0;
	
	if(MaxCycleTime < CycleTime)
	{
		MaxCycleTime = CycleTime;
	}
	CycleTime = 0;
	TimeFlag = 0;
	if(TimeFlagIRQ)
	{
		TimeFlagIRQ = 0;
        TimeFlag |= TIME_Min;
		
		uc10msCnt ++;
        if(uc10msCnt >= (10000/TIME_MIN_US))
		{
			TimeFlag |= TIME_10ms;
			uc10msCnt = 0;

			uc100msCnt ++;
            if (uc100msCnt >= 10)
			{
				TimeFlag |= TIME_100ms;		
				uc100msCnt = 0;
				
				uc1sCnt ++;
                if (uc1sCnt >= 10)
				{
					TimeFlag |= TIME_1s;		
					uc1sCnt = 0;

					uc1minCnt ++ ;
					if (uc1minCnt >= 60)				
					{
						TimeFlag |= TIME_1Min;		
						uc1minCnt = 0;						
					}
				}
			}
		}
    }
}

/**************************************************************
//Fuction void TimeProc(void)
//Desrition:时间总函数
//Input:  
//Output:
//Author:陈首敏
***************************************************************/
unsigned long GetMaxCycleTime(void)
{
	return MaxCycleTime;
}